package com.example.video.util.laixiOperate;



import com.example.video.util.DeviceEncode;
import com.example.video.util.websocket.WebSocketService;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
public class LAIXICmd {
    @Value("${LAIXI.filePath}")
    private String downloadPath;

    @Value("${LAIXI.server}")
    private String laixiURL;

    /**
     * 获取待绑定的分组id；如果没有，则创建
     * @return 待绑定分组的id
     */
    public  String cmdGetCacheGroup() throws URISyntaxException, InterruptedException {
        String groupId = null;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action","GetGroup");
        JSONObject json = new JSONObject(WebSocketService.sendCmd(laixiURL, jsonObject.toString()));
        JSONArray jsonArray = new JSONArray(json.getString("result"));
        boolean flag = false;
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject item = jsonArray.getJSONObject(i);
            String groupName = item.getString("groupName");
            if ("待绑定账号".equals(groupName)) {
                flag = true;
                groupId = String.valueOf(item.getInt("id"));
                break;
                // 在这里对找到的对象进行进一步处理
            }
        }

        // 如果没有找到待绑定分组，则创建
        if(!flag){
            JSONObject jsonRes = new JSONObject(cmdCreateGroup("待绑定账号"));
             groupId = jsonRes.getString("result");
        }
        return groupId;
    }

    /**
     * 设置设备id到设备剪切板
     * @param deviceIds 设备id列表
     * @return {string} JSONArray的string。来喜服务端返回的信息
     */
    public  String cmdSetIdToClip(List<String> deviceIds) throws URISyntaxException, InterruptedException {
        JSONArray array = new JSONArray();
        if(deviceIds == null || deviceIds.size() == 0){
            String rs = "";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("StatusCode", "400");
            Map<String,String> map = new HashMap<>();
            map.put("errmsg","传入的设备id为空，错误！");
            jsonObject.put("result",map);
            array.put(jsonObject);
        }else{
            deviceIds.forEach(item ->{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("action","writeclipboard");
                Map<String, String> map = new HashMap<>(4);
                map.put("deviceIds", item);
                map.put("content",item);
                jsonObject.put("comm",map);
                JSONObject json = null;
                try {
                    json = new JSONObject(WebSocketService.sendCmd(laixiURL, jsonObject.toString()));
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                json.put("deviceId",item);
                array.put(json);
            });
        }
        return array.toString();
    }

    /**
     * 执行脚本的来喜命令发送给来喜服务端
     * @TODO 将文件路径修改成从配置文件中获取
     * @param deviceIds 需要执行的设备id数组，若传空数组或者是null，则显示所以设备
     * @param name 执行的脚本文件名，没有.js 后缀
     * @return 返回从来喜服务端返回的json格式化后的字符串
     */
    public String cmdExcuJs(List<String> deviceIds, String name) throws URISyntaxException, InterruptedException {
        String idList = "";
        if(deviceIds == null || deviceIds.size() == 0){
            idList = "all";
        }else{
            idList = String.join(",", deviceIds);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action","ExecuteAutoJs");
        Map<String, String> map = new HashMap<>(4);
        map.put("deviceIds", idList);
        map.put("filePath",downloadPath+"/files/"+name+".js");
        jsonObject.put("comm",map);

        return WebSocketService.sendCmd(laixiURL, jsonObject.toString());
    }


    /**
     * 获取分组列表
     * @return 返回从来喜服务端返回的json格式化后的字符串
     */
    public  String cmdGetGroup() throws URISyntaxException, InterruptedException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action","GetGroup");
        return WebSocketService.sendCmd(laixiURL, jsonObject.toString());
    }


    /**
     * 创建一个分组
     * @param name 创建的分组名
     * @return 返回从来喜服务端返回的json格式化后的字符串
     */
    public  String cmdCreateGroup(String name) throws URISyntaxException, InterruptedException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action","CreateGroup");
        Map<String, String> map = new HashMap<>(4);
        map.put("groupName", name);
        jsonObject.put("comm",map);
        return WebSocketService.sendCmd(laixiURL, jsonObject.toString());
    }

    /**
     * 查看所有设备
     * @return 返回从来喜服务端返回的json格式化后的字符串
     */
    public  String cmdGetDeviceIds() throws URISyntaxException, InterruptedException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action","List");
        return WebSocketService.sendCmd(laixiURL, jsonObject.toString());
    }

    /**
     * 移动设备到某分组
     * @param preGroup 移动前分组id，默认分组为0
     * @param aftGroup 移动后分组id
     * @param deviceIds 需要移动的设备id数组
     * @return 返回从来喜服务端返回的json格式化后的字符串
     */
    public  String cmdMvDeviceToGroup(String preGroup, String aftGroup, List<String> deviceIds) throws URISyntaxException, InterruptedException {
        String idlist = String.join(",", deviceIds);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action","RemoveDeviceGroup");
        Map<String, String> map = new HashMap<>(4);
        map.put("deleteGroupId", preGroup);
        map.put("newGroupId", aftGroup);
        map.put("androidIds", idlist);

        jsonObject.put("comm",map);
        return WebSocketService.sendCmd(laixiURL, jsonObject.toString());
    }

    /**
     * 查看设备的详情
     * @param deviceIds 设备id列表
     * @return 返回从来喜服务端返回的json格式化后的字符串
     */
    public  String cmdGetDevicesDetail(List<String> deviceIds) throws URISyntaxException, InterruptedException {
        String idList = "";
        if(deviceIds == null || deviceIds.size() == 0){
            idList = "all";
        }else{
            idList = String.join(",", deviceIds);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action","Detail");
        Map<String ,String > map = new HashMap<>(4);
        map.put("deviceIds",idList);

        jsonObject.put("comm", map);
        return WebSocketService.sendCmd(laixiURL, jsonObject.toString());
    }

    /**
     * 查看分组下的设备
     * @param groupName 分组名
     */
    public  String cmdGetDevicesByGroupId(String groupName) throws JsonProcessingException, URISyntaxException, InterruptedException {
        JSONObject jsonObject = new JSONObject(cmdGetGroup());
        JSONArray jsonArray = new JSONArray(jsonObject.get("result").toString());
//        log.info(jsonArray);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            if(jsonObject1.get("groupName").toString().equals(groupName)){
                return jsonObject1.get("androidIds").toString();
            }
        }
        return jsonObject.toString();
    }


    // TODO:
    public  String cmdAdbWriteIdFile(String deviceId)  throws URISyntaxException, InterruptedException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action","adb");
        Map<String ,String > map = new HashMap<>(4);
        map.put("deviceIds",deviceId);
        map.put("command","touch /sdcard/Download/"+ DeviceEncode.encodeFileName(deviceId) +".id");
        jsonObject.put("comm", map);
        log.info("写入设备id："+jsonObject);
        return WebSocketService.sendCmd(laixiURL, jsonObject.toString());
    }

    public String cmdSendHttp(String deviceId,String url, String fileName ) throws URISyntaxException, InterruptedException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("action","HttpDown");
        Map<String ,String > map = new HashMap<>(4);
        map.put("deviceIds",deviceId);
        map.put("httpurl", url);
        map.put("savepath", "/sdcard/Download/" + fileName);
        jsonObject.put("comm", map);
        log.info("使手机下载id文件："+jsonObject);
        return WebSocketService.sendCmd(laixiURL, jsonObject.toString());
    }
}
